<template>

	<custom-header/>
	
<view class="container">
		<view class="header">
			<view class="tabs">
				<button v-for="(tab, index) in tabs" :key="index" :class="{ active: currentTab === tab }"
					@click="currentTab = tab" class="tab-btn" style="">
					{{ tab }}
				</button>
			</view>
		</view>

		<view class="waterfall-container" ref="waterfallContainer">
			<view class="waterfall-column" v-for="(column, columnIndex) in columnCount" :key="columnIndex">
				<waterfall-item v-for="(item, index) in itemsInColumns[columnIndex]" :key="item.imageUrl + index"
					:image-url="getImageUrl(item.imageUrl)" :title="item.title" :author="item.author" :avatr="item.avatr"

					:column-width="columnWidth" @loaded="handleImageLoaded(columnIndex, $event)">
				</waterfall-item>
			</view>
			
		</view>
		<view class="no-more">
			没有更多了
		</view>

		<custom-nav :navs="navs" :current-nav="currentNav" @nav-change="handleNavChange"></custom-nav>


	</view>
</template>

<script>
import CustomHeader from '@/components/header.vue';
import waterfallItem from '@/components/waterfall-item.vue'
import CustomNav from '@/components/nav.vue';
export default {
	components: {
		waterfallItem,
		CustomNav,
		CustomHeader
	},
	data() {
		return {
			tabs: ['推荐', '最新', '线稿', '抽象', '素描', '速写', '厚涂', 'AI生成',],
			currentTab: '推荐',

			navs: [
				{ label: '首页', value: 'home' },
				{ label: '社区', value: 'community' },
				{ label: '消息', value: 'message' },
				{ label: '我的', value: 'me' }
			],
			currentNav: 'home',
			items: [{
				imageUrl: 'https://t.alcy.cc/mp?id=1',
				title: '新作品，请大家多多指教',
				avatr: 'https://t.alcy.cc/mp?id=1',

				author: '二号画师',
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=2',
				title: '尝试了一下这种画风',
				avatr: 'https://t.alcy.cc/mp?id=2',

				author: '一号画师'
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=3',
				title: '接小QQ人，有意者私聊',
				avatr: 'https://t.alcy.cc/mp?id=3',

				author: '三号画师'
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=4',
				avatr: 'https://t.alcy.cc/mp?id=4',

				title: '周末摸鱼作品',
				author: '四号画师'
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=5',
				avatr: 'https://t.alcy.cc/mp?id=5',

				title: '新的绘画风格尝试',
				author: '五号画师'
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=6',
				avatr: 'https://t.alcy.cc/mp?id=6',
				title: '完成一单，展示一下121222222222222',
				author: '六号画师'
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=7',
				avatr: 'https://t.alcy.cc/mp?id=7',

				title: '今日份练习',
				author: '一号画师'
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=8',
				avatr: 'https://t.alcy.cc/mp?id=8',

				title: '原创角色设计',
				author: '二号画师'
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=9',
				avatr: 'https://t.alcy.cc/mp?id=9',

				title: '练习',
				author: '三号画师'
			},
			{
				imageUrl: 'https://t.alcy.cc/mp?id=10',
				avatr: 'https://t.alcy.cc/mp?id=10',

				title: '又完成一单',
				author: '三号画师'
			}
			],
			columnHeights: [], // 记录每列的高度
			itemsInColumns: [], // 记录每列中的项目
			columnCount: 2, // 默认列数
			columnWidth: 0 // 每列的宽度
		}
	},
	computed: {
		filteredItems() {
			// 实现标签筛选功能
			if (this.currentTab === '推荐' || this.currentTab === '最新') {
				return this.items;
			}
			// 这里可以根据实际需求修改筛选逻辑
			return this.items.filter(item => item.tags && item.tags.includes(this.currentTab));
		}
	},
	methods: {
		// 处理底部导航切换事件（从组件接收）
		handleNavChange(navName) {
			this.currentNav = navName;
			// 可在此添加导航切换后的逻辑（如页面跳转、数据刷新等）
			console.log('切换到：', navName);
		},
		// 处理图片路径，适配不同平台
		getImageUrl(path) {
			// #ifdef H5
			return path;
			// #endif

			// #ifdef MP-WEIXIN
			// 微信小程序中，直接使用网络图片URL
			if (path.startsWith('http')) {
				return path;
			}
			// 对于本地图片才使用/static路径
			return '/static' + path.replace('/static', '');
			// #endif

			return path;
		},

		// 重新分配项目到各列
		redistributeItems() {
			// 初始化列
			this.itemsInColumns = Array.from({
				length: this.columnCount
			}, () => []);
			this.columnHeights = Array(this.columnCount).fill(0);

			// 按高度分配项目
			this.filteredItems.forEach(item => {
				// 找到高度最小的列
				const minHeight = Math.min(...this.columnHeights);
				const minIndex = this.columnHeights.indexOf(minHeight);

				// 将项目添加到该列
				this.itemsInColumns[minIndex].push(item);

				// 更精确的预估高度：假设平均宽高比为1.5，加上文字区域高度60px
				this.columnHeights[minIndex] += (this.columnWidth * 1.5) + 60;
			});
		},

		// 处理图片加载完成事件
		handleImageLoaded(columnIndex, height) {
			// 计算实际高度与预估高度的差值
			const estimatedHeight = (this.columnWidth * 1.5) + 60;
			const actualHeight = height + 60; // 图片实际高度 + 文字区域高度
			const diff = actualHeight - estimatedHeight;

			// 只修正差值，避免重复计算
			this.columnHeights[columnIndex] += diff;
		},

		calculateColumnWidth() {
			return new Promise(resolve => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.waterfall-container').boundingClientRect(data => {
					if (data) {
						const containerWidth = data.width;
						const columnGap = 16 * (this.columnCount - 1);
						this.columnWidth = (containerWidth - columnGap) / this.columnCount;
						resolve(this.columnWidth);
					}
				}).exec();
			});
		}
	},
	onLoad() {
		// 获取系统信息，确定列数
		const {
			windowWidth
		} = uni.getSystemInfoSync();
		if (windowWidth >= 1200) {
			this.columnCount = 4;
		} else if (windowWidth >= 768) {
			this.columnCount = 3;
		} else {
			this.columnCount = 2;
		}

		// 关键修复：确保DOM渲染完成后再初始化，使用异步流程
		this.$nextTick(async () => {
			await this.calculateColumnWidth();
			this.redistributeItems();
		});

		// 监听窗口大小变化
		uni.onWindowResize((res) => {
			if (res.size.windowWidth >= 1200) {
				this.columnCount = 4;
			} else if (res.size.windowWidth >= 768) {
				this.columnCount = 3;
			} else {
				this.columnCount = 2;
			}

			this.$nextTick(async () => {
				await this.calculateColumnWidth();
				this.redistributeItems();
			});
		});
	},
	onUnload() {
		uni.offWindowResize();
	},
	watch: {
		filteredItems: {
			handler() {
				this.$nextTick(() => {
					this.redistributeItems();
				});
			},
			immediate: true
		},
		columnCount() {
			this.$nextTick(async () => {
				await this.calculateColumnWidth();
				this.redistributeItems();
			});
		}
	}
}
</script>

<style>
.container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	max-width: 100vw;
	background-color: #ffffff;
	/* 添加顶部内边距，避免内容被固定导航栏遮挡 */
	padding-top: 40px;
	box-sizing: border-box;
}
.no-more{
	text-align: center;
	padding: 20px;
	font-size: 12px;
	color: #999;
	margin-top: 80px;
	clear: both;
}


/* 顶部导航栏固定样式 */
.header {
	position: fixed;
	overflow-x: scroll;
	/* 固定定位 */
	top: 82px;
	/* 距离顶部0 */
	left: 0;
	right: 0;
	/* 左右占满屏幕宽度 */
	background-color: #fff;
	padding: 1vw;
	z-index: 999;
	/* 确保在其他内容上方 */
	width: 100%;
	/* 确保宽度正确 */
}

.header::-webkit-scrollbar {

	display: none;
	overflow-x: auto;
	/* 隐藏滚动条但保留功能 */
	scrollbar-width: none;
	-webkit-overflow-scrolling: touch;
}

.title {
	font-size: 24px;
	font-weight: bold;
	display: block;
	margin-bottom: 6px;
}


.tabs {
	display: flex;
	/* width: 130vw; */
	height: 30px;
}



.tab-btn {
	background: none;
	border: none;
	border-radius: 0;
	padding: 0vw 8vw;
	font-size:15px;
	border-bottom: 2px solid transparent;
	white-space: nowrap;
	display: flex;
	align-items: center;
	justify-content: center;
}

button::after {
	border: none;
}

button {
	position: relative;
	display: block;
	margin-left: auto;
	margin-right: auto;
	padding-left: 0px;
	padding-right: 0px;
	box-sizing: border-box;
	text-align: center;
	text-decoration: none;
	line-height: 1.35;
	-webkit-tap-highlight-color: transparent;
	overflow: hidden;
	color: #000;
	font-size: 32rpx;
	background-color: #fff;
	width: 100%;
	height: 100%;
}




.tab-btn.active {
	color:var(--dominant-hue);
	font-weight: bolder;
}

.waterfall-container {
	display: flex;
	gap: 10px;
	padding: 16px;
	flex: 1;
	box-sizing: border-box;
	position: relative;
	top: 65px;
}

.waterfall-column {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 10px;
}

/* 确保瀑布流项不会超出列宽 */
::v-deep .waterfall-item {
	width: 100%;
	box-sizing: border-box;
	break-inside: avoid;
	/* 防止项目被分割 */
}

::v-deep .waterfall-item img {
	width: 100%;
	height: auto;
	display: block;
}
</style>